<template>
  <div>
    <el-dialog title="批量导入简历" :visible.sync="dialogVisible" :fullscreen="true" :before-close="handleClose" append-to-body>
      <!-- :before-upload="beforeUpload" -->
      <el-upload
        class="upload-demo"
        ref="uploadResume"
        :auto-upload="false"
        action="/api/uploadFiles"
        :headers="headers"
        :data="formData"
        :file-list="resumeList"
        :http-request="handleUploadFile"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :on-error="uploadError"
        multiple
        >
        <el-button :disabled="addFileDisable" class="el-icon-upload" slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button :disabled="sumbitDisable" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      
      </el-upload>
      <hr style="height:1px;border:none;border-top:1px solid ; color:#939393; width:100%;" />
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-row type="flex"  justify="space-between">
            <el-col :span="8">文件名</el-col>
            <el-col :span="4">大小</el-col>
            <el-col :span="4">错误信息</el-col>
            <el-col :span="4">完成情况</el-col>
          </el-row>
        </div>
        <div>
          <el-row type="flex" justify="space-between" v-for="(item, index) in showResumeList" :key="index" >
            <el-col :span="8">{{item.name}}</el-col>
            <el-col :span="4">{{item.size | sizefilter}}</el-col>
            <el-col :span="4">{{ item.error_info ? item.error_info : '' }}</el-col>
            <el-col :span="4">{{item.status}}</el-col>
          </el-row> 
        </div>
      </el-card>
    </el-dialog> 

  </div>
</template>

<script>
import API from '@/utils/backend_api'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  name: 'uploadResumeDialog',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false // 这样可以指定默认的值
    }
  },
  data() {
    return {
      dedup_policy: 'save',
      headers: {
        Authorization: getToken(),
        smail: '*_~'
      },
      resumeList: [
      ],
      formData: {
        task_id: '',
        resumes: []
      },
      showResumeList: [],
      dialogVisible: false,
      addFileDisable: false,
      sumbitDisable: false,
      current_notify_url: ''
    }
  },
  computed: {
    ...mapGetters([
      'socket'
    ])
  },
  watch: {
    visible: function(val, oldVal) {
      console.log('当前值为：' + val, '旧值为：' + oldVal)
      this.dialogVisible = val
    },
    socket: {
      handler(val, oldVal) {
        if (val.message && val.message !== '') {
          const msgObj = JSON.parse(val.message)
          console.log('candidate msgObj =', msgObj)
          /* 处理通知，刷新消息通知 */
          if (msgObj.type && msgObj.type === 'upload') {
            for (const resume of this.showResumeList) {
              if (resume.uid === Number(msgObj.uid)) {
                if (msgObj.code === 200) {
                  resume.status = msgObj.content
                  resume.is_handle = true
                  const index = this.showResumeList.indexOf(resume)
                  this.showResumeList.splice(index, 1, resume)
                }
                if (msgObj.code === 400) {
                  resume.status = msgObj.content
                  resume.error_info = msgObj.error_info
                  resume.is_handle = true
                  const index = this.showResumeList.indexOf(resume)
                  this.showResumeList.splice(index, 1, resume)
                }
              }
            }
            console.log('candidate=', this.showResumeList)
            for (const resume of this.showResumeList) {
              if (resume.is_handle) {
                continue
              } else {
                return
              }
            }
            this.addFileDisable = false
            this.sumbitDisable = false
          }
        }
      },
      deep: true
    }
  },
  created() {
  },
  filters: {
    sizefilter: function(limit) {
      let size = ''
      if (limit === 0 || limit === '0') {
        size = '0B'
      } else if (limit < 0.1 * 1024) {
        // 如果小于0.1KB转化成B
        size = limit.toFixed(2) + 'B'
      } else if (limit < 0.1 * 1024 * 1024) {
        // 如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        // 如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
      } else {
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }
      const sizestr = size + ''
      const len = sizestr.indexOf('\.')
      const dec = sizestr.substr(len + 1, 2)
      if (dec === '00') {
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
      }
      return sizestr
    }
  },
  methods: {
    uploadError(response) {
      console.log('--------- uploadError--------')
      this.formData = {
        task_id: '',
        resumes: []
      }
      this.addFileDisable = false
      this.sumbitDisable = false
    },
    handleUploadFile(param) {
      console.log('--- handleUploadFile -----', param)
      const that = this
      if (param.file && param.file.uid) {
        for (const resume of this.showResumeList) {
          if (resume.uid === param.file.uid) {
            const index = this.showResumeList.indexOf(resume)
            console.log('------', index)
            const fileObj = param.file
            // 接收上传文件的后台地址
            const FileController = param.action
            // FormData 对象
            const form = new FormData()
            // 文件对象
            form.append('file', fileObj)
            // 其他参数
            form.append('dedup_policy', that.dedup_policy) // ignore
            const notify_url = 'http://system.mnc-management.com:8333/api/candidate/task/' + resume.task_id + '/resume/' + resume.uuid
            form.append('notify_url', notify_url)
            form.append('token', getToken())
            // XMLHttpRequest 对象
            const xhr = new XMLHttpRequest()
            xhr.open('post', FileController, true)
            xhr.setRequestHeader('Authorization', getToken())
            xhr.upload.addEventListener('progress', function name(params) {
              console.log('form-------', params)
              // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
              if (params.lengthComputable) {
                resume.status = '上传中' + Math.round(params.loaded / params.total * 100) + '%'
                that.showResumeList.splice(index, 1, resume)
              }
            }, false)
            xhr.onload = function() {
              console.log('success')
              resume.status = '正在处理中'
              that.showResumeList.splice(index, 1, resume)
            }
            xhr.send(form)
          }
        }
      }
    },
    submitUpload() {
      if (this.showResumeList.length === 0) {
        this.$message({
          showClose: true,
          message: '上传文件不能为空',
          type: 'warning'
        })
      }
      API.candidate.resume({ files: JSON.stringify(this.showResumeList) }).then(response => {
        this.addFileDisable = true
        this.sumbitDisable = true
        console.log('------ submitUpload------', response.data)
        if (response.data && response.data.task_id && response.data.resumes) {
          console.log(this.showResumeList)
          console.log(response.data.resumes)
          this.showResumeList.forEach(resume => {
            response.data.resumes
              .filter(x => { return Number(x.uid) === resume.uid })
              .forEach(x => {
                resume.task_id = response.data.task_id
                resume.uuid = x.uuid
                console.log('resume:', resume)
              })
          })
        }
        this.$refs.uploadResume.submit()
      })
    },
    handleClose(done) {
      this.$emit('closeDialog', { type: 'cancel', data: {}})
    },
    removeResume(file_uid) {
      console.log('this.resumeList==', this.resumeList)
      if (this.resumeList && file_uid) {
        this.showResumeList = this.showResumeList.filter(item => {
          return item.uid && (Number(item.uid) !== Number(file_uid))
        })
      }
    },
    handleRemove(file, fileList) {
      this.showResumeList = fileList.map(item => {
        return {
          uid: item.uid,
          name: item.name,
          percentage: item.percentage,
          size: item.size,
          status: item.status,
          dedup_policy: this.dedup_policy
        }
      })
    },
    handleChange(file, fileList) {
      if (fileList && fileList.length > 0) {
        this.showResumeList = fileList.map(item => {
          return {
            uid: item.uid,
            name: item.name,
            percentage: item.percentage,
            size: item.size,
            status: item.status,
            dedup_policy: this.dedup_policy
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 10px;
}
</style>
